package com.rivues.module.manage.web.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.model.DataDic;
import com.rivues.module.platform.web.model.Organ;
import com.rivues.module.platform.web.model.Role;
import com.rivues.module.platform.web.model.RoleGroup;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.platform.web.model.UserOrgan;
import com.rivues.module.platform.web.model.UserRole;
import com.rivues.util.RivuTools;
import com.rivues.util.iface.authz.UserAuthzFactory;

/**
 * 平安UM导入实现
 * @author leon
 *
 */
@Service
public class AccountServiceUMImpl extends AccountServiceAbs implements AccountService{
	/**
	 * log4j
	 */
	private final Logger logger = LoggerFactory.getLogger(AccountServiceUMImpl.class);
	
	/**
	 * 导入实现
	 * @param sheet
	 * @param orgi
	 * @param creater
	 * @throws Exception
	 */
	protected  List<String> processImport(HSSFWorkbook workbook,String orgi,String creater) throws Exception{
		return this.processUserImport(workbook.getSheetAt(0), orgi, creater);
	}
	/**
	 * 用户导入实现
	 * @param sheet
	 * @param orgi
	 * @param creater
	 * @throws Exception
	 */
	protected  List<String> processUserImport(Sheet sheet,String orgi,String creater) throws Exception{
		List<String> users = new ArrayList<String>();
		if (sheet == null) return users;
		
		logger.info("导入用户开始，sheet包含用户数量为:"+sheet.getLastRowNum());
		for (int i = 2; i <= sheet.getLastRowNum(); i++) {
			// 登录名
			String loginname = getStringCellValue(sheet.getRow(i).getCell(0));
			User user = UserAuthzFactory.getInstance(orgi).getUser(loginname, orgi);
			String username = getStringCellValue(sheet.getRow(i).getCell(1));
			int count = RivuDataContext.getService().getCountByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("organ",loginname)).add(Restrictions.eq("orgi",orgi)));
			if (StringUtils.isBlank(loginname)||user==null||count>0) {
				users.add(loginname);
				continue;
			}
			if(!StringUtils.isBlank(username)&&!"".equals(username)){
				user.setNickname(username);
				user.setFirstname(username);
			}
			
			user.setUsername(loginname);
			user.setCreater(creater);
			user.setCreatetime(new Date());	
			user.setOrgan(loginname);
			user.setOrgi(orgi);
			
			RivuDataContext.getService().saveIObject(user);
			UserOrgan ur = new UserOrgan();
			ur.setOrganid("0");
			ur.setOrgi(orgi);
			ur.setUserid(user.getId());
			RivuDataContext.getService().saveIObject(ur);
			// 用户角色
			String cellValue = getStringCellValue(sheet.getRow(i).getCell(2));
			Role role= this.getRole(cellValue, orgi, creater);
			
			if(role!=null){
				UserRole userrole = new UserRole();
				userrole.setOrgi(orgi);
				userrole.setRoleid(role.getId());
				userrole.setUserid(user.getId());
				RivuDataContext.getService().saveIObject(userrole);
			}
			
		}
		return users;
	}
	private Role getRole(String roleStr,String orgi,String creater){
		Role role  = null;
		
		if (roleStr==null||"".equals(roleStr)||"/".equals(roleStr)) return role;
		roleStr = roleStr.substring(1, roleStr.length());
		String[] roles = roleStr.split("/");
		
		List<RoleGroup> groups = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(RoleGroup.class).add(Restrictions.eq("orgi",orgi)));
		String parent = "0" ;
		RoleGroup group = null;
		for (int i = 0; i < roles.length; i++) {
			
			if(i==roles.length-1){
				List<Role> rolelist = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Role.class).add(Restrictions.eq("groupid",parent)).add(Restrictions.eq("name",roles[i])).add(Restrictions.eq("orgi",orgi)));
				if(rolelist.size()>0){
					role = rolelist.get(0);
				}else{
					role = new Role();
					role.setCreater(creater);
					role.setCreatetime(new Date());
					role.setGroupid(parent);
					role.setOrgi(orgi);
					role.setName(roles[i]);
					role.setUpdatetime(new Date());
					RivuDataContext.getService().saveIObject(role);
				}
			}else if(i==0){
				group = this.getRoleGroup(roles[i], "0", groups);
			}else{
				group = this.getRoleGroup(roles[i], group.getId(), groups);
			}
			//如果没检索到创建分组
			if(group==null){
				group = new RoleGroup();
				group.setCreater(creater);
				group.setCreatetime(new Date());
				group.setName(roles[i]);
				group.setOrgi(orgi);
				group.setParentid(parent);
				RivuDataContext.getService().saveIObject(group);
			}
			parent = group.getId();
		}
		return role;
	}
	/**
	 * 查询数据库里存不存在相应的角色
	 * @param name
	 * @param parentId
	 * @param groups
	 * @return
	 */
	private RoleGroup getRoleGroup(String name,String parentId,List<RoleGroup> groups){
		RoleGroup group = null;
		for (int i = 0; i < groups.size(); i++) {		
			if(groups.get(i).getName().equals(name)&&groups.get(i).getParentid().equals(parentId)){
				group = groups.get(i);
				break;
			}
		}
		return group;
	}
	
	
	
	private Map<String, String> getDbUser(String orgi){
		Map<String, String> map = new HashMap<String, String>();
		List<User> list = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("orgi", orgi)));
		if (list != null && list.size()>0){
			for(User user : list){
				map.put(user.getUsername(), user.getUsername());
			}
		}
		return map;
		
	} 
	
	/**
	 * 导入角色
	 * @param roleMap
	 * @param creater
	 * @param orgi
	 * @return
	 */
	private Map<String, Role> insertRole(Map<String, String[]> roleMap,String creater,String orgi){
		Map<String, Role> returnMap = new HashMap<String, Role>();
		if(roleMap.isEmpty()) return returnMap;
		Set<String> insertSets = new HashSet<String>();
		for(String key : roleMap.keySet()){
			String groupId = "0";
			String[] strs = roleMap.get(key);
			if(strs.length>1){
				//处理角色组
				for(int i=0;i<strs.length-1;i++){
					RoleGroup group = new RoleGroup();
					group.setId(UUID.randomUUID().toString().replaceAll("-", ""));
					group.setCreatetime(new Date());
					group.setName(strs[i]);
					group.setCreater(creater);
					group.setOrgi(orgi);
					group.setParentid(groupId);
					if(insertSets.contains(group.getName()+group.getParentid()))continue;
					List<RoleGroup> list = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(RoleGroup.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("name",group.getName())).add(Restrictions.eq("parentid", groupId)));
					if(list != null && list.size() >0){
						groupId = list.get(0).getId();
						continue;
					}
					RivuDataContext.getService().saveIObject(group);
					insertSets.add(group.getName()+group.getParentid());
					groupId = group.getId();
				}
				//保存角色
				saveRole(groupId, orgi, strs[strs.length-1], creater, returnMap);
			} else {
				//保存角色
				saveRole(groupId, orgi, strs[strs.length-1], creater, returnMap);
			}
		}
		logger.info("导入角色结束，导入数量为:"+returnMap.size());
		return returnMap;
	}
	
	private Role saveRole(String groupId,String orgi,String name,String creater,Map<String, Role> map){
		//处理角色
		Role role = new Role();
		role.setCreater(creater);
		role.setCreatetime(new Date());
		role.setGroupid(groupId);
		role.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		role.setName(name);
		role.setOrgi(orgi);
		List list = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Role.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("name",role.getName())).add(Restrictions.eq("groupid", groupId)));
		if(list != null && list.size() >0) return null;
		RivuDataContext.getService().saveIObject(role);
		map.put(role.getName(), role);
		return role;
	}
	/**
	 * 导入组织信息
	 * @param organMap
	 */
	private Map<String,Organ> processOrgan(Map<String,String[]> organMap,String creater,String orgi){
		Map<String , Organ> insertMap = new HashMap<String, Organ>();
		if(organMap.isEmpty()) return insertMap;
		for(String key:organMap.keySet()){
			String[] str=organMap.get(key);
			int i=0;
			String parentId = "0";
			while(i<str.length){
				Organ organ = new Organ();
				organ.setId(UUID.randomUUID().toString().replaceAll("-", ""));
				organ.setCreater(creater);
				organ.setCreatetime(new Date());
				organ.setName(str[i]);
				organ.setParentid(parentId); 
				organ.setOrgi(orgi);
				List<Organ> list = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("name",organ.getName())).add(Restrictions.eq("parentid", parentId)));
				if(list != null && list.size() >0) {
					i++;
					parentId = list.get(0).getId();
					continue;
				}
				parentId = organ.getId();
				RivuDataContext.getService().saveIObject(organ);
				insertMap.put(str[i], organ);
				i++;
			}
		}
		logger.info("导入组织结束，导入数量为:"+insertMap.size());
		return insertMap;
	}

	

}
